package com.sparrow.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import com.sparrow.constant.COMMON;
import com.sparrow.enums.LOG_LEVEL;
import com.sparrow.utils.DateTimeUtil;
import com.sparrow.utils.FileUtil;
import com.sparrow.utils.StringUtil;

public class Log {
	private static Log log = new Log();

	public static Log getInstance() {
		return log;
	}

	public void warm(String log) {
		this.writeLog(log, LOG_LEVEL.WARM);
	}

	public void info(String log) {
		this.writeLog(log, LOG_LEVEL.INFO);
	}

	public void error(Exception exception, boolean isLimitLog) {
		this.error(exception, null, isLimitLog);
	}

	public void error(Throwable exception) {
		this.error(exception, null, true);
	}

	public void error(Throwable exception, String prefixLog) {
		this.error(exception, prefixLog, false);
	}

	public void error(Throwable exception, String prefixLog,
			boolean isLimitLogLength) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		exception.printStackTrace(pw);
		StringBuffer exceptionString = new StringBuffer();
		if (!StringUtil.isNullOrEmpty(prefixLog)) {
			exceptionString.append(prefixLog);
			exceptionString.append(COMMON.ENTER_TEXT);
		}
		exceptionString.append(sw.toString());
		this.writeLog(exceptionString.toString(), LOG_LEVEL.ERROR);
	}

	/**
	 * 写日志文件。日志文件被入到WebRoot/errorlog.txt
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param str
	 * @throws IOException
	 */
	private synchronized void writeLog(String str, LOG_LEVEL logLevel) {
		try {
			String path = FileUtil.getInstance().getWebRootPhysicPath() + "log";
			File directory = new File(path);
			if (!directory.exists()) {
				directory.mkdirs();
			}

			FileOutputStream fileOutputStream = new FileOutputStream(path
					+ String.format("/log%1$s.log",
							DateTimeUtil.getFormatCurrentTime("yyyyMMdd")),
					true);

			fileOutputStream.write((logLevel.toString() + "|"
					+ DateTimeUtil.getFormatCurrentTime() + COMMON.ENTER_TEXT)
					.getBytes("UTF-8"));
			fileOutputStream.write((str + COMMON.ENTER_TEXT).getBytes("UTF-8"));
			fileOutputStream
					.write(("--------------------------------------------------------------" + COMMON.ENTER_TEXT)
							.getBytes("UTF-8"));
			fileOutputStream.flush();
			fileOutputStream.close();
			System.out.println(str);
		} catch (Exception e) {
		}
	}
}
